<template>
  <el-card shadow="never">
      <!-- 搜索栏 -->
      <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="queryParams.roleName"
            placeholder="请输入角色名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input
            v-model="queryParams.roleKey"
            placeholder="请输入权限字符"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 240px">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
        </el-row>

      <!-- 数据表格 Pro -->
      <DataTable 
        :data="roleList"
        :columns="tableColumns"
        :loading="loading"
        :pagination="paginationConfig"
        :on-page-change="handlePageChange"
        show-toolbar
        show-selection
        show-index
        column-resizable
        setting-id="system-app-role-management"
        :max-height="600"
        stripe
        border
        @selection-change="handleSelectionChange"
        @refresh="getList"
        @search-toggle="showSearch = $event"
      >
        <!-- 状态列插槽 -->
        <template #status="{ row }">
          <el-switch
            v-model="row.status"
            active-value="0"
            inactive-value="1"
            :before-change="() => handleStatusBeforeChange(row)"
          />
        </template>

        <!-- 创建时间列插槽 -->
        <template #createTime="{ row }">
          <span>{{ proxy.parseTime(row.createTime) }}</span>
        </template>

        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <template v-if="row.roleId !== 1">
            <el-button link type="primary" size="small" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, row)">
              <el-button link type="primary" size="small">更多</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleDataScope">数据权限</el-dropdown-item>
                  <el-dropdown-item command="handleAuthUser">分配用户</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </template>
      </DataTable>
    </el-card>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item prop="roleKey">
          <template #label>
            <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
            权限字符
          </template>
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="roleSort">
          <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="(val) => handleCheckedTreeExpand(val, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="(val) => handleCheckedTreeNodeAll(val, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="(val) => handleCheckedTreeConnect(val, 'menu')">父子联动</el-checkbox>
          <el-tree
            ref="menuRef"
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog v-model="openDataScope" :title="title" width="500px" append-to-body>
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
            <el-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.dataScope == 2" label="数据权限">
          <el-checkbox v-model="deptExpand" @change="(val) => handleCheckedTreeExpand(val, 'dept')">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="(val) => handleCheckedTreeNodeAll(val, 'dept')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.deptCheckStrictly" @change="(val) => handleCheckedTreeConnect(val, 'dept')">父子联动</el-checkbox>
          <el-tree
            ref="deptRef"
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDataScope">确 定</el-button>
          <el-button @click="cancelDataScope">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, getCurrentInstance, computed } from 'vue';
import { listRole, getRole, delRole, addRole, updateRole, dataScope, changeRoleStatus, deptTreeSelect } from '@/api/system/role';
import { treeselect as menuTreeselect, roleMenuTreeselect } from '@/api/system/menu';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ElTree } from 'element-plus';

defineOptions({
  name: 'Role',
});

const { proxy } = getCurrentInstance() as any;

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<number[]>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 角色表格数据
const roleList = ref<any[]>([]);
// 弹出层标题
const title = ref('');
// 是否显示弹出层
const open = ref(false);
// 是否显示弹出层（数据权限）
const openDataScope = ref(false);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
// 日期范围
const dateRange = ref<any[]>([]);

// 数据范围选项
const dataScopeOptions = ref([
  { value: '1', label: '全部数据权限' },
  { value: '2', label: '自定数据权限' },
  { value: '3', label: '本部门数据权限' },
  { value: '4', label: '本部门及以下数据权限' },
  { value: '5', label: '仅本人数据权限' },
]);

// 菜单列表
const menuOptions = ref<any[]>([]);
// 部门列表
const deptOptions = ref<any[]>([]);

// DataTable Pro 列配置
const tableColumns = [
  { dataIndex: 'roleId', label: '角色编号', width: 220, align: 'center', 'show-overflow-tooltip': true },
  { dataIndex: 'roleName', label: '角色名称', width: 150, 'show-overflow-tooltip': true },
  { dataIndex: 'roleKey', label: '权限字符', width: 150, 'show-overflow-tooltip': true },
  { dataIndex: 'roleSort', label: '显示顺序', width: 120, align: 'center' },
  { dataIndex: 'status', label: '状态', width: 100, slot: 'status', align: 'center' },
  { dataIndex: 'createTime', label: '创建时间', width: 180, slot: 'createTime' },
  { dataIndex: 'action', label: '操作', slot: 'action', width: 200, fixed: 'right', align: 'center' }
];

// 查询参数
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  roleName: undefined,
  roleKey: undefined,
  status: undefined,
});

// 表单参数
const form = ref<any>({});

const defaultProps = {
  children: 'children',
  label: 'label',
};

// 表单校验
const rules = reactive({
  roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
  roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
  roleSort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }],
});

const queryFormRef = ref();
const formRef = ref();
const menuRef = ref<InstanceType<typeof ElTree>>();
const deptRef = ref<InstanceType<typeof ElTree>>();

// 分页配置
const paginationConfig = computed(() => ({
  pageNum: queryParams.value.pageNum,
  pageSize: queryParams.value.pageSize,
  total: total.value
}));

// 分页变化处理
const handlePageChange = async (page: number, size: number) => {
  queryParams.value.pageNum = page;
  queryParams.value.pageSize = size;
  return await getList();
};

/** 查询角色列表 */
async function getList() {
  loading.value = true;
  console.log('开始获取角色列表，查询参数:', proxy.addDateRange(queryParams.value, dateRange.value));
  try {
    const response = await listRole(proxy.addDateRange(queryParams.value, dateRange.value));
    console.log('角色列表API返回数据:', response);
    roleList.value = response.rows || response.data?.rows || [];
    total.value = response.total || response.data?.total || 0;
    console.log('设置后的角色列表:', roleList.value);
    console.log('设置后的总数:', total.value);
  } catch (error) {
    console.error('获取角色列表失败:', error);
  } finally {
    loading.value = false;
  }
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then((response: any) => {
    console.log('菜单树选择API返回数据:', response);
    menuOptions.value = response.data || response;
    console.log('设置后的菜单选项:', menuOptions.value);
  });
}

// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  if (!menuRef.value) return [];
  // 目前被选中的菜单节点
  const checkedKeys = menuRef.value.getCheckedKeys() as number[];
  // 半选中的菜单节点
  const halfCheckedKeys = menuRef.value.getHalfCheckedKeys() as number[];
  checkedKeys.unshift(...halfCheckedKeys);
  return checkedKeys;
}

// 所有部门节点数据
function getDeptAllCheckedKeys() {
  if (!deptRef.value) return [];
  // 目前被选中的部门节点
  const checkedKeys = deptRef.value.getCheckedKeys() as number[];
  // 半选中的部门节点
  const halfCheckedKeys = deptRef.value.getHalfCheckedKeys() as number[];
  checkedKeys.unshift(...halfCheckedKeys);
  return checkedKeys;
}

/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId: number) {
  return roleMenuTreeselect(roleId).then((response: any) => {
    console.log('角色菜单树选择API返回数据:', response);
    menuOptions.value = response.data?.menus || response.menus || [];
    console.log('设置后的菜单选项:', menuOptions.value);
    return response;
  });
}

/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId: number) {
  return deptTreeSelect(roleId).then((response: any) => {
    deptOptions.value = response.depts;
    return response;
  });
}

// 角色状态切换前的确认和处理
function handleStatusBeforeChange(row: any): Promise<boolean> {
  return new Promise((resolve, reject) => {
    // 切换后的状态文本（因为 before-change 是切换前调用，所以要反着来）
    const text = row.status === '0' ? '停用' : '启用';
    const roleName = row.roleName || row.name || '该';
    
    console.log('handleStatusBeforeChange - row对象:', row);
    console.log('handleStatusBeforeChange - roleName:', roleName);
    
    ElMessageBox.confirm(`确认要"${text}"角色"${roleName}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        // 用户确认，执行状态切换
        const newStatus = row.status === '0' ? '1' : '0';
        changeRoleStatus(row.roleId, newStatus)
    .then(() => {
      ElMessage.success(text + '成功');
            resolve(true); // 允许开关切换
    })
          .catch(() => {
            ElMessage.error(text + '失败');
            reject(false); // 阻止开关切换
          });
      })
      .catch(() => {
        // 用户取消
        reject(false); // 阻止开关切换
      });
    });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 取消按钮（数据权限）
function cancelDataScope() {
  openDataScope.value = false;
  reset();
}

// 表单重置
function reset() {
  if (menuRef.value) {
    menuRef.value.setCheckedKeys([]);
  }
  if (deptRef.value) {
    deptRef.value.setCheckedKeys([]);
  }
  menuExpand.value = false;
  menuNodeAll.value = false;
  deptExpand.value = true;
  deptNodeAll.value = false;
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: '0',
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined,
  };
  formRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryFormRef.value?.resetFields();
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map((item) => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 更多操作触发
function handleCommand(command: string, row: any) {
  switch (command) {
    case 'handleDataScope':
      handleDataScope(row);
      break;
    case 'handleAuthUser':
      handleAuthUser(row);
      break;
    default:
      break;
  }
}

// 树权限（展开/折叠）
function handleCheckedTreeExpand(value: any, type: string) {
  if (type == 'menu') {
    const treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      if (menuRef.value && menuRef.value.store && menuRef.value.store.nodesMap) {
        const node = menuRef.value.store.nodesMap[treeList[i].id];
        if (node) {
          node.expanded = value;
        }
      }
    }
  } else if (type == 'dept') {
    const treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      if (deptRef.value && deptRef.value.store && deptRef.value.store.nodesMap) {
        const node = deptRef.value.store.nodesMap[treeList[i].id];
        if (node) {
          node.expanded = value;
        }
      }
    }
  }
}

// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value: any, type: string) {
  if (type == 'menu') {
    if (menuRef.value) {
      menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
    }
  } else if (type == 'dept') {
    if (deptRef.value) {
      deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
    }
  }
}

// 树权限（父子联动）
function handleCheckedTreeConnect(value: any, type: string) {
  if (type == 'menu') {
    form.value.menuCheckStrictly = value ? true : false;
  } else if (type == 'dept') {
    form.value.deptCheckStrictly = value ? true : false;
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getMenuTreeselect();
  open.value = true;
  title.value = '添加角色';
}

/** 修改按钮操作 */
function handleUpdate(row?: any) {
  reset();
  const roleId = row?.roleId || ids.value[0];
  const roleMenu = getRoleMenuTreeselect(roleId);
  getRole(roleId).then((response: any) => {
    form.value = response.data;
    console.log('角色数据:', response.data);
    console.log('menuCheckStrictly:', form.value.menuCheckStrictly);
    
    // 确保 menuCheckStrictly 和 deptCheckStrictly 是布尔值
    if (typeof form.value.menuCheckStrictly === 'string') {
      form.value.menuCheckStrictly = form.value.menuCheckStrictly === 'true';
    } else if (form.value.menuCheckStrictly === undefined || form.value.menuCheckStrictly === null) {
      form.value.menuCheckStrictly = true; // 默认值
    }
    
    if (typeof form.value.deptCheckStrictly === 'string') {
      form.value.deptCheckStrictly = form.value.deptCheckStrictly === 'true';
    } else if (form.value.deptCheckStrictly === undefined || form.value.deptCheckStrictly === null) {
      form.value.deptCheckStrictly = true; // 默认值
    }
    
    console.log('处理后的 menuCheckStrictly:', form.value.menuCheckStrictly);
    console.log('处理后的 deptCheckStrictly:', form.value.deptCheckStrictly);
    
    open.value = true;
    nextTick(() => {
      roleMenu.then((res: any) => {
        console.log('角色菜单树选择API返回数据:', res);
        const checkedKeys = res.data?.checkedKeys
        console.log('checkedKeys:', checkedKeys);
        if (checkedKeys && Array.isArray(checkedKeys)) {
          checkedKeys.forEach((v: number) => {
            nextTick(() => {
              if (menuRef.value) {
                menuRef.value.setChecked(v, true, false);
              }
            });
          });
        } else {
          console.warn('checkedKeys 不是数组或为空:', checkedKeys);
        }
      });
    });
  });
  title.value = '修改角色';
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value: string) {
  if (value !== '2' && deptRef.value) {
    deptRef.value.setCheckedKeys([]);
  }
}

/** 分配数据权限操作 */
function handleDataScope(row: any) {
  reset();
  const deptTreeSelectData = getDeptTree(row.roleId);
  getRole(row.roleId).then((response: any) => {
    form.value = response.data;
    openDataScope.value = true;
    nextTick(() => {
      deptTreeSelectData.then((res: any) => {
        const checkedKeys = res.data?.checkedKeys || res.checkedKeys;
        if (deptRef.value && checkedKeys && Array.isArray(checkedKeys)) {
          deptRef.value.setCheckedKeys(checkedKeys);
        }
      });
    });
  });
  title.value = '分配数据权限';
}

/** 分配用户操作 */
function handleAuthUser(row: any) {
  // this.$router.push("/system/role-auth/user/" + row.roleId);
  ElMessage.info('分配用户功能待实现');
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.roleId != undefined) {
        form.value.menuIds = getMenuAllCheckedKeys();
        updateRole(form.value).then(() => {
          ElMessage.success('修改成功');
          open.value = false;
          getList();
        });
      } else {
        form.value.menuIds = getMenuAllCheckedKeys();
        addRole(form.value).then(() => {
          ElMessage.success('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交按钮（数据权限） */
function submitDataScope() {
  if (form.value.roleId != undefined) {
    form.value.deptIds = getDeptAllCheckedKeys();
    dataScope(form.value).then(() => {
      ElMessage.success('修改成功');
      openDataScope.value = false;
      getList();
    });
  }
}

/** 删除按钮操作 */
function handleDelete(row?: any) {
  const roleIds = row?.roleId || ids.value.join(',');
  ElMessageBox.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(function () {
      return delRole(roleIds);
    })
    .then(() => {
      getList();
      ElMessage.success('删除成功');
    });
}

function handleExport() {
  proxy.download(
    'system/role/export',
    {
      ...queryParams.value,
    },
    `role_${new Date().getTime()}.xlsx`
  );
}

// 初始化
getList();
</script>

<style scoped lang="scss">
@use '@/styles/common.scss';

.tree-border {
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #ffffff none;
  border-radius: 4px;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
}

// 优化卡片间距
.el-card {
  margin-bottom: 8px;
  
  :deep(.el-card__body) {
    padding: 12px;
  }
}

// 优化搜索表单间距
.el-form {
  margin-bottom: 8px;
  
  .el-form-item {
    margin-bottom: 12px;
  }
}

// 优化按钮组间距
.el-row.mb8 {
  margin-bottom: 8px;
}

// 彻底清除 Element Plus 默认样式
:deep(.el-row) {
  margin-left: 0 !important;
  margin-right: 0 !important;
  margin: 0 !important;
  
  .el-col {
    padding-right: 0 !important;
  }
}

// 覆盖所有可能的 Element Plus 默认 gutter 样式
:deep(.el-row[style*="margin-left"]) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

// 优化对话框表单间距
:deep(.el-dialog) {
  .el-form {
    .el-form-item {
      margin-bottom: 22px; // 增加底部间距以容纳错误信息
      
      // 当有错误信息时，调整间距
      &.is-error {
        margin-bottom: 24px;
        
        .el-form-item__error {
          margin-top: 2px;
          font-size: 12px;
          line-height: 1.2;
          padding: 0;
        }
      }
      
      // 当没有错误信息时，保持紧凑间距
      &:not(.is-error) {
        margin-bottom: 18px;
      }
    }
    
    .el-row {
      margin-bottom: 0;
      
      .el-col {
        padding-left: 8px;
        padding-right: 8px;
        
        &:first-child {
          padding-left: 0;
        }
        
        &:last-child {
          padding-right: 0;
        }
      }
    }
  }
  
  .el-dialog__body {
    padding: 20px 20px 0 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px 20px;
    text-align: right;
    
    .el-button + .el-button {
      margin-left: 8px;
    }
  }
}
</style>
